package com.pricl.wechat.faq.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pricl.frame.common.utils.EmojiDealUtil;
import com.pricl.wechat.faq.dao.FaqUserDao;
import com.pricl.wechat.faq.entity.FaqUser;
import com.pricl.wechat.faq.entity.criteria.FaqUserCriteria;
import com.pricl.wechat.faq.service.FaqUserService;
import com.pricl.wechat.faq.util.AdminUtil;
import com.pricl.wechat.faq.util.MyWxConfig;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.bean.WxUserList.WxUser;
import com.soecode.wxtools.bean.result.WxOAuth2AccessTokenResult;
import com.soecode.wxtools.exception.WxErrorException;
import com.vdurmont.emoji.EmojiParser;

import net.minidev.json.JSONObject;

/**
 * toekn校验过滤器，所有的API接口请求都要经过该过滤器
 *
 */

@WebFilter(urlPatterns="/wechat/faq/*")
public class Wechat_Faq_Filter1_checkToken  implements Filter {
	/**
	 * 用户service
	 */
	@Autowired
	FaqUserService faqUserService;
	
	/**
	 * 用户dao
	 */
	@Autowired
	FaqUserDao faqUserDao;
	
	private IService iService = new WxService();
	
	@Override
	public void doFilter(ServletRequest argo, ServletResponse arg1,
			FilterChain chain ) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) argo;
		HttpServletResponse resp=(HttpServletResponse) arg1;
		
		//测试用
		/*if (true) {
			req.getSession().setAttribute("id", 93L);
			// 判断当前用户是否为管理员，是的话加入session标识
			if (AdminUtil.INSTANCE.checkIsAdminUser(93L)) {
				req.getSession().setAttribute("isAdmin", true);
			}
			chain.doFilter(req, resp);
			return;
		}*/
		
		
		// 判断用户是否授权过 /******修改由服务号提供授权支持改为开放平台授权支持******/
		String openid = String.valueOf(req.getSession().getAttribute("openid"));
		String code = req.getParameter("code");
		 try {
			 // 如果未携带code且没有openid则不进入授权页面
			if ("null".equals(openid) && StringUtils.isEmpty(code)) {
				
				// 检查cookie中是否存在用户id，有则直接跳过授权。
				Cookie[] cookies = req.getCookies();
				if (cookies != null) {
					for (Cookie c : cookies) {
						if ("chigua_wx_id".equals(c.getName()) && StringUtils.isNotEmpty(c.getValue()) ) {
							FaqUser user = faqUserService.selectByPrimaryKey(Long.valueOf(c.getValue()));
							req.getSession().setAttribute("id", Long.valueOf(c.getValue()));
							req.getSession().setAttribute("openid", user.getOpenid());
							// 判断当前用户是否为管理员，是的话加入session标识
							if (AdminUtil.INSTANCE.checkIsAdminUser(user.getId())) {
								req.getSession().setAttribute("isAdmin", true);
							}

							chain.doFilter(req, resp);
							return;
						}
					}
				}
				
				//String oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe6f9e31fe8e10a8d&redirect_uri=http%3A%2F%2Fwinton.imwork.net%2Fwechat%2Ffaq%2Findex&response_type=code&scope=snsapi_login&state=#wechat_redirect";  
				String oauthUrl = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=#wechat_redirect", MyWxConfig.getInstance().getAppId(),MyWxConfig.getInstance().getRedirecturl());
                System.out.println(oauthUrl);  
                resp.sendRedirect(oauthUrl);  
                return; 
			} else if ("null".equals(openid)) { // 如果有code，但是没有openid说明授权通过，已获得code，可以根据code获取用户信息并插入或者更新 
				String str = iService.post("https://api.weixin.qq.com/sns/oauth2/access_token", String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code",MyWxConfig.getInstance().getAppId(),MyWxConfig.getInstance().getAppSecret(),code));  
				WxOAuth2AccessTokenResult result = WxOAuth2AccessTokenResult.fromJson(str);
				WxUser wechatuser = WxUser.fromJson(iService.post("https://api.weixin.qq.com/sns/userinfo", String.format("access_token=%s&openid=%s", result.getAccess_token(),result.getOpenid())));
				
				// 用户信息操作
				long userId = checkHasUser(req, result, wechatuser);
				// 存当前的openid到session
				req.getSession().setAttribute("openid", result.getOpenid());
				req.getSession().setAttribute("id", userId);
				// 存当前id到cookie
				Cookie idCookie = new Cookie("chigua_wx_id", String.valueOf(userId));
				idCookie.setMaxAge(86400);// 设置token有效期一天
				resp.addCookie(idCookie);
				// 判断当前用户是否为管理员，是的话加入session标识
				if (AdminUtil.INSTANCE.checkIsAdminUser(userId)) {
					req.getSession().setAttribute("isAdmin", true);
				}
				
				chain.doFilter(req, resp);
				return;
			} else { // 其他的则直接跳过进入业务逻辑处理
				chain.doFilter(req, resp);
				return;
			}
       } catch (WxErrorException e) {
           e.printStackTrace();
       } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public void output(JSONObject resultJson,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();  
		out.write(mapper.writeValueAsString(resultJson));
		out.flush();
		out.close();
		
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("过滤器初始化");
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, arg0.getServletContext());
	}

	@Override
	public void destroy() {
		
	}
	
	/**
	 * 添加/更新用户信息
	 * @param req
	 * @param result
	 * @param wechatuser
	 */
	private Long checkHasUser(HttpServletRequest req, WxOAuth2AccessTokenResult result, WxUser wechatuser) {
		// 转换用户vo
		FaqUser faqUser = new FaqUser();
		faqUser.setCreateTime(new Date());
		faqUser.setEnable(0);
		faqUser.setGender(wechatuser.getSex() == 1 ? "男" : wechatuser.getSex() == 2 ? "女" : "未知");
		faqUser.setHeadurl(wechatuser.getHeadimgurl());
		if (!StringUtils.isEmpty(EmojiDealUtil.getEmojiUnicodeString(wechatuser.getNickname()))) {
			faqUser.setName(EmojiParser.removeAllEmojis(wechatuser.getNickname()));
		} else {
			faqUser.setName(wechatuser.getNickname());
		}
		faqUser.setOpenid(wechatuser.getOpenid());
		faqUser.setToken(result.getAccess_token());
		
		// 判断
		FaqUserCriteria fuc = new FaqUserCriteria();
		fuc.setOpenidEqualTo(result.getOpenid());
		List<FaqUser> checkFaqUser = faqUserService.selectByEntity(fuc);
		if (checkFaqUser == null || checkFaqUser.size() == 0) {
			// 插入用户数据
			faqUserService.insert(faqUser);
			return faqUser.getId();
		} else {
			faqUserDao.updateByPrimaryKeySelective(faqUser);
			return checkFaqUser.get(0).getId();
		}
	}
	
}
